package com.jeesite.modules.dataScreen.config;

import cn.hutool.core.collection.ConcurrentHashSet;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TableNameInterceptor implements InnerInterceptor {

    private static final String file_Path = "./table.txt";


    //定义多指map
    public static final Set<String> TABLE_NAMES = new ConcurrentHashSet<>();

    private static final Pattern TABLE_NAME_PATTERN = Pattern.compile("from\\s+([\\w\\.\\w]+)\\s+", Pattern.CASE_INSENSITIVE);

    public TableNameInterceptor() {
        try {
            List<String> strings = FileUtil.readLines(new File(file_Path), StandardCharsets.UTF_8);
            TABLE_NAMES.addAll(strings);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        String sql = boundSql.getSql();
        Matcher matcher = TABLE_NAME_PATTERN.matcher(sql);
        String peek = DynamicDataSourceContextHolder.peek();
        if (matcher.find()) {
            String group = matcher.group(1);
            String tableName = StrUtil.format("{}#{}", peek, group);
            if (!TABLE_NAMES.contains(tableName)) {
                TABLE_NAMES.add(tableName);
                FileUtil.appendString(tableName + "\n", new File(file_Path), StandardCharsets.UTF_8);
            }
        }
    }

}
